package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.FocusUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.FocusUserApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.server.interceptors.UserHolder;
import com.tanhua.vo.CommentVo;
import com.tanhua.vo.PageResult;
import com.tanhua.vo.VideoVo;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class VideoService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Reference
    private VideoApi videoApi;
    @Reference
    private UserInfoApi userInfoApi;

    @CacheEvict(value = "videoList",allEntries = true)
    public ResponseEntity saveSmallVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws Exception {
//        1、把图片上传到阿里云
        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
//        2、把小视频上传到FASTDFS

//        File file = new File("d://1576134125940400.mp4");
//        InputStream inputStream = new FileInputStream(file);

//        获取图片的扩张名
//       获取文件名最后一个点后面的内容
        String fileName = videoFile.getOriginalFilename();
        String extname = fileName.substring(fileName.lastIndexOf(".") + 1);

        StorePath storePath = storageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), extname, null);//InputStream inputStream, long fileSize B, String fileExtName, Set<MetaData> metaDataSet
        String videoUrl = fdfsWebServer.getWebServerUrl()+storePath.getFullPath();

        Video video = new Video();
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        video.setText("1231213");//
        video.setUserId(UserHolder.getUserId());
//        video.setCreated();
//        video.setVid();
//        video.setId();

        videoApi.save(video);

        return ResponseEntity.ok(null);


    }

    //@Cacheable(value = "videoList",key = "#page+'_'+#pagesize")
//    默认就是把当前方法返回的结果存储到redis中
    public PageResult querySmallVideos(Integer page, Integer pagesize) {

//        1、直接查询redis
//                如果redis中没有 再查数据库 放到redis中

      PageResult pageResult = videoApi.querySmallVideos(page,pagesize);



        List<Video> videoList = (List<Video>) pageResult.getItems();

        List<VideoVo> list = new ArrayList<>();
        for (Video video : videoList) {
            Long userId = video.getUserId();
            UserInfo userInfo = userInfoApi.findById(userId);

            if(userInfo==null){
                continue;
            }

            VideoVo videoVo = new VideoVo();

//            videoVo.setHasLiked();


            videoVo.setSignature(video.getText());
            videoVo.setCover(video.getPicUrl()); //封面
            videoVo.setId(video.getId().toString());
            videoVo.setUserId(userId);
            videoVo.setLikeCount(video.getLikeCount());
            videoVo.setCommentCount(video.getCommentCount());
            videoVo.setVideoUrl(video.getVideoUrl());
            videoVo.setAvatar(userInfo.getAvatar());
            videoVo.setNickname(userInfo.getNickname());

            if(redisTemplate.hasKey("video_focus_"+UserHolder.getUserId()+"_"+userId)){
                videoVo.setHasFocus(0);
            }else{
                videoVo.setHasFocus(1);
            }

            if (redisTemplate.hasKey("publish_video_like_"+video.getId()+"_"+UserHolder.getUserId())){
                videoVo.setHasLiked(0);
            }else {
                videoVo.setHasLiked(1);
            }

            list.add(videoVo);
        }

        pageResult.setItems(list);

        return pageResult;


    }

    @Reference
    private FocusUserApi focusUserApi;

    @Autowired
    private StringRedisTemplate redisTemplate;



    @CacheEvict(value = "videoList",allEntries = true)
    public ResponseEntity userFocus(Long focusUserId) {

//        向 user_focus表中插入一条数据
//        FocusUser focusUser = new FocusUser();
//        focusUser.setId();
//        focusUser.setCreated();
//        focusUser.setFocusUserId();
//        focusUser.setUserId();
        focusUserApi.save(UserHolder.getUserId(),focusUserId);

        redisTemplate.boundValueOps("video_focus_"+UserHolder.getUserId()+"_"+focusUserId).set("");

        return ResponseEntity.ok(null);

    }
    @CacheEvict(value = "videoList",allEntries = true)
    public ResponseEntity userUnFocus(Long focusUserId) {
        focusUserApi.delete(UserHolder.getUserId(),focusUserId);

        redisTemplate.delete("video_focus_"+UserHolder.getUserId()+"_"+focusUserId);
        return ResponseEntity.ok(null);
    }

    //对小视频点赞
    //@CacheEvict(value = "videoList",allEntries = true)  //清除缓存
    public ResponseEntity videoLike(String videoId) {

        Video video = new Video();
        video.setId(new ObjectId(videoId));

        Long userId = UserHolder.getUserId();  //当前登陆人的id
        Integer count = videoApi.saveVideo(video,userId);

        //把当前登录人对这个圈子的点赞存储到redis中    如果redis中有这个key 就表示当前登录人对这个圈子已经点赞了
        redisTemplate.boundValueOps("publish_video_like_"+new ObjectId(videoId)+"_"+UserHolder.getUserId()).set("");
        return ResponseEntity.ok(count);

    }

    //对小视频取消点赞
    //@CacheEvict(value = "videoList",allEntries = true)  //清除缓存
    public ResponseEntity videoDislike(String videoId) {
        Video video = new Video();
        video.setId(new ObjectId(videoId));

        Long userId = UserHolder.getUserId();  //当前登陆人的id
        Integer count = videoApi.deleteVideo(video,userId);

        //删除当前登录人对这个圈子的喜欢标记
        redisTemplate.delete("publish_video_like_"+new ObjectId(videoId)+"_"+UserHolder.getUserId());

        return ResponseEntity.ok(count);

    }

    @Reference
    private CommentApi commentApi;

    //小视频发评论
    public ResponseEntity saveComments(String videoId, String comment) {

        Comment comment1 = new Comment();
        comment1.setUserId(UserHolder.getUserId());  //评论人的id
        comment1.setPublishId(new ObjectId(videoId));
        comment1.setCommentType(5)  ;//1-动态点赞，2-动态评论，3-动态喜欢 4-视频点赞  5-视频评论  6-评论点赞
        comment1.setContent(comment);  //小视频的评论内容
        Integer count = commentApi.saveComment(comment1);

        return ResponseEntity.ok(count);

    }

    //分页查询小视频评论
    public ResponseEntity queryComments(String videoId, Integer page, Integer pagesize) {
        PageResult pageResult = videoApi.queryComments(videoId,page,pagesize);
        List<Comment> commentList = (List<Comment>) pageResult.getItems();

        List<CommentVo> list = new ArrayList<>();
        for (Comment comment : commentList) {
            Long userId = comment.getUserId();
            UserInfo userInfo = userInfoApi.findById(userId);

            CommentVo commentVo = new CommentVo();
            BeanUtils.copyProperties(userInfo, commentVo);
            BeanUtils.copyProperties(comment, commentVo);

            commentVo.setId(comment.getId().toString());
            commentVo.setCreateDate(new SimpleDateFormat("HH:mm").format(new Date(comment.getCreated())));
            list.add(commentVo);
        }
        pageResult.setItems(list);
        return ResponseEntity.ok(pageResult);

    }
}
